﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Eqwww.Code;
using Eqwww.Data;
using Eqwww.Domain;
using Eqwww.Domain.Models.SystemManage;
using Microsoft.EntityFrameworkCore;

namespace Eqwww.App.SystemManage
{
    public class JobApp
    {
        private ApplicationDbContext _context;
        private IModelHandler _modelHandler;
        private DatabaseLogApp _dbLogApp;
        public JobApp(ApplicationDbContext context, IModelHandler modelHandler, DatabaseLogApp databaseLogApp)
        {
            _context = context;
            _modelHandler = modelHandler;
            _dbLogApp = databaseLogApp;
        }

        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ModelResult> CreateAsync(JobModel model)
        {
            if (IsExistCode(model.Code))
                return Common.ErrorResult("编码已经存在");


            _modelHandler.Create(model);
            _context.Sys_Jobs.Add(model);
            _dbLogApp.LogCreateInformation(model.Id, model, "创建工种");
            await _context.SaveChangesAsync();
            return Common.SuccessResult();
        }

        /// <summary>
        /// 更新策略
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ModelResult> UpdateAsync(JobModel model)
        {
            var oldModel = await GetAsync(model.Id);
            if (oldModel == null)
                return Common.ErrorResult("未找到要更新的实体");
            
            if (IsExistCode(model.Code, model.Id))
                return Common.ErrorResult("编码已经存在");

            oldModel.Code = model.Code;
            oldModel.Name = model.Name;
            oldModel.SortCode = model.SortCode;

            _modelHandler.Update(oldModel);
            _context.Sys_Jobs.Update(oldModel);
            _dbLogApp.LogUpdateInformation(oldModel.Id, oldModel, "更新工种");
            await _context.SaveChangesAsync();
            return Common.SuccessResult();
        }

        /// <summary>
        /// 移除工种，当工种包含岗位时不允许移除
        /// </summary>
        /// <param name="jobId"></param>
        /// <returns></returns>
        public async Task<ModelResult> RemoveAsync(string jobId)
        {

            var model = _context.Sys_Jobs.FirstOrDefault(x => x.Id == jobId);
            if (model == null)
                return Common.ErrorResult("指定Id的工种不存在");

            if (_context.Sys_Posts.Any(x => x.JobId == jobId && x.DeleteMark != true))
                return Common.ErrorResult("当前工种正在被岗位引用，不能移除");

            _modelHandler.Delete(model);
            _context.Sys_Jobs.Update(model);
            _dbLogApp.LogRemoveInformation(jobId, model, "逻辑删除工种");
            await _context.SaveChangesAsync();
            return Common.SuccessResult();
        }

        

        public async Task<JobModel> GetAsync(string id, bool containDeleted = false)
        {
            var expression = ExtLinq.True<JobModel>();
            if (!containDeleted)
                expression = expression.And(x => x.DeleteMark != true);
            expression = expression.And(x => x.Id == id);
            return await _context.Sys_Jobs.AsNoTracking().Include(x=>x.CreateUser).Include(x=>x.LastUpdateUser).Include(x=>x.DeleteUser).FirstOrDefaultAsync(expression);
        }

        /// <summary>
        /// 检查指定code是否存在
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool IsExistCode(string code)
        {
            return _context.Sys_Jobs.Any(x => x.Code.ToLower() == code.ToLower());
        }

        /// <summary>
        /// 检查指定code是否存在
        /// </summary>
        /// <param name="code"></param>
        /// <param name="strategoryId"></param>
        /// <returns></returns>
        public bool IsExistCode(string code, string strategoryId)
        {
            return _context.Sys_Jobs.Any(x => x.Code.ToLower() == code.ToLower() && x.Id != strategoryId);
        }

        public IList<JobModel> GetPagedList(string keyword, Pagination pagination)
        {
            var exp = ExtLinq.True<JobModel>();
            exp = exp.And(x => x.DeleteMark != true);
            if (!string.IsNullOrEmpty(keyword))
                exp = exp.And(x => x.Name.Contains(keyword));
            var data = _context.FindQueryable(exp, pagination)
                .Include(x => x.CreateUser);
            return data.ToList();
        }

        /// <summary>
        /// 岗位选择器
        /// </summary>
        /// <returns></returns>
        public IList<TreeCollapseModel> GetTreeCollapseItems()
        {
            var jobs = _context.IQueryable<JobModel>().Where(x => x.DeleteMark != true);
            var result = (from item in jobs
                          select new TreeCollapseModel
                          {
                              Id = item.Id,
                              Text = item.Name,
                              ParentId = null,
                              SortCode = item.SortCode,
                              Url = null
                          }).ToList();
            return result;
        }
    }
}
